package me.xue.communityhealth.admin.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.log4j.Log4j2;
import me.xue.communityhealth.data.Pager;
import me.xue.communityhealth.model.Drug;
import me.xue.communityhealth.service.*;
import me.xue.communityhealth.util.ApplicationUtil;
import me.xue.communityhealth.util.FileUtil;
import me.xue.communityhealth.util.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.Date;

@Controller
@Log4j2
public class DrugController {

    private final DrugService drugService;
    private final DrugUnitService drugUnitService;
    private final DrugDepotService drugDepotService;
    private final DrugPlaceService drugPlaceService;
    private final DrugSupplierService drugSupplierService;
    private final DrugTypeService drugTypeService;

    @Autowired
    public DrugController(DrugService drugService,
                          DrugUnitService drugUnitService,
                          DrugDepotService drugDepotService,
                          DrugPlaceService drugPlaceService,
                          DrugSupplierService drugSupplierService,
                          DrugTypeService drugTypeService) {
        this.drugService = drugService;
        this.drugUnitService = drugUnitService;
        this.drugDepotService = drugDepotService;
        this.drugPlaceService = drugPlaceService;
        this.drugSupplierService = drugSupplierService;
        this.drugTypeService = drugTypeService;
    }

    private void init(Model model) {
        model.addAttribute("drugUnits", drugUnitService.findAll());
        model.addAttribute("drugDepots", drugDepotService.findAll());
        model.addAttribute("drugPlaces", drugPlaceService.findAll());
        model.addAttribute("drugSuppliers", drugSupplierService.findAll());
        model.addAttribute("drugTypes", drugTypeService.findAll());
    }

    @GetMapping("/drugs")
    public String all(@RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
                      Model model) {
        //TODO 每页查询数可配置
        PageHelper.startPage(page, 15);
        Page<Drug> drugPage = drugService.pagedDrugs();
        model.addAttribute("drugs", drugPage.getResult());
        PageInfo pageInfo = drugPage.toPageInfo();
        Pager pager = new Pager(pageInfo.getPages(), pageInfo.getPageNum());
        model.addAttribute("pager", pager);
        return "drugs";
    }

    @GetMapping("/drug/add")
    public String addPage(Model model) {
        init(model);
        model.addAttribute("drug", new Drug());
        return "drug_edit";
    }

    @PostMapping("/drug")
    public String add(@Valid Drug drug, BindingResult bindingResult,
                      @RequestParam(value = "photoFile", required = false, defaultValue = "null") MultipartFile multipartFile,
                      Model model) {
        if (bindingResult.hasErrors()) {
            log.error("添加药品失败: {}", bindingResult.getAllErrors());
            init(model);
            return "drug_edit";
        }
        drug.setPhoto(drugService.savePhoto(multipartFile, getName(drug.getName())));
        int saved = drugService.save(drug);
        if (saved == 1) {
            return "redirect:/drugs";
        }
        return "drug_edit";
    }

    @GetMapping("/drug/{id:\\d+}/edit")
    public String updatePage(@PathVariable("id") Integer id, Model model) {
        Drug drug = drugService.findOne(id);
        init(model);
        model.addAttribute("drug", drug);
        return "drug_edit";
    }

    @PutMapping("/drug")
    public String update(@Valid Drug drug, BindingResult bindingResult,
                         @RequestParam(value = "photoFile", required = false, defaultValue = "null") MultipartFile multipartFile,
                         Model model) {
        if (bindingResult.hasErrors()) {
            log.error("更新药品失败: {}", bindingResult.getAllErrors());
            init(model);
            return "drug_edit";
        }
        if (multipartFile != null && !multipartFile.isEmpty()) {
            log.info("multipart file name + " + multipartFile.getOriginalFilename());
            drug.setPhoto(FileUtil.saveMultipartFile(multipartFile, ApplicationUtil.getDrugPath().getAbsolutePath(), drug.getPhoto()));
        }
        int updated = drugService.update(drug);
        if (updated == 1) {
            return "redirect:/drugs";
        }
        return "drug_edit";
    }

    @DeleteMapping("/drug/{id:\\d+}")
    @ResponseBody
    public String delete(@PathVariable("id") Integer id) {
        Drug drug = drugService.findOne(id);
        int deleted = drugService.delete(id);
        if (deleted == 1) {
            drugService.deletePhoto(drug.getPhoto());
            return "success";
        }
        return "fail";
    }

    private String getName(String orig) {
        return Md5Util.getHashKey(orig + new Date().toString());
    }
}
